package com.geek.project.geekverificationcodestarter.service.sms.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.geek.project.geekverificationcodestarter.exception.SmsException;
import com.geek.project.geekverificationcodestarter.props.SmsProperties;
import com.geek.project.geekverificationcodestarter.service.sms.SmsService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AliYunSmsServiceImpl implements SmsService {

    private SmsProperties smsProperties;

    public AliYunSmsServiceImpl(SmsProperties smsProperties) {
        this.smsProperties = smsProperties;
    }

    /**
     * 发送短信验证码
     *
     * @author geek
     * @param phone 电话号码
     * @param templateCode 验证码
     * @return
     */
    @Override
    public String sendSms(String phone, String templateCode, String templateParamJson) {
        IAcsClient client = new DefaultAcsClient(smsProperties.getProfile());
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", smsProperties.getSignName());
        request.putQueryParameter("TemplateCode", smsProperties.getTemplateCode().get(templateCode));
        request.putQueryParameter("TemplateParam", templateParamJson);
        try {
            if (smsProperties.isEnabled()) {
                CommonResponse response = client.getCommonResponse(request);
                log.info("短信发送响应数据:{}",response.getData());
                return response.getData();
            }else {
                log.info("短信服务已关闭:{}",templateParamJson);
                return templateParamJson;
            }
        } catch (ServerException e) {
            log.error("短信服务异常",e);
            throw new SmsException("短信服务异常", e);
        } catch (ClientException e) {
            log.error("客户端连接异常",e);
            throw new SmsException("客户端连接异常", e);
        }
    }

}
